import {trim} from 'lodash';
import handlebars from 'handlebars/dist/handlebars';
//让其它电脑的浏览器通过本机打印（适用例子）：
var head = document.head || document.getElementsByTagName("head")[0] || document.documentElement;
var loadjs = function (js, cb) {
    var oscript = document.createElement("script");
    oscript.src = js;
    head.insertBefore(oscript, head.firstChild);
    oscript.onerror = function () {
        if (cb) {
            cb(0);
        }
    };
    oscript.onload = oscript.onreadystatechange = function () {
        if (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete') {
            if (cb) {
                cb(1);
            }
        }
    };
    oscript.onload = oscript.onreadystatechange = null;
}
var CreatedOKLodop7766 = null;

var tplInfo = {width: 794, height: 1123};
var editors = {}, editorChangeTimer;
//====判断是否需要安装CLodop云打印服务器:====
function needCLodop() {
    try {
        var ua = navigator.userAgent;
        if (ua.match(/Windows\sPhone/i) != null) return true;
        if (ua.match(/iPhone|iPod/i) != null) return true;
        if (ua.match(/Android/i) != null) return true;
        if (ua.match(/Edge\D?\d+/i) != null) return true;
        if (ua.match(/QQBrowser/i) != null) return false;
        var verTrident = ua.match(/Trident\D?\d+/i);
        var verIE = ua.match(/MSIE\D?\d+/i);
        var verOPR = ua.match(/OPR\D?\d+/i);
        var verFF = ua.match(/Firefox\D?\d+/i);
        var x64 = ua.match(/x64/i);
        if ((verTrident == null) && (verIE == null) && (x64 !== null))
            return true; else if (verFF !== null) {
            verFF = verFF[0].match(/\d+/);
            if (verFF[0] >= 42) return true;
        } else if (verOPR !== null) {
            verOPR = verOPR[0].match(/\d+/);
            if (verOPR[0] >= 32) return true;
        } else if ((verTrident == null) && (verIE == null)) {
            var verChrome = ua.match(/Chrome\D?\d+/i);
            if (verChrome !== null) {
                verChrome = verChrome[0].match(/\d+/);
                if (verChrome[0] >= 42) return true;
            }
            ;
        }
        ;
        return false;
    } catch (err) {
        return true;
    }
    ;
};

function printCheck() {
    //====页面引用CLodop云打印必须的JS文件：====
    if (needCLodop()) {
        loadjs("http://localhost:8000/CLodopfuncs.js?priority=1", function (flag) {
            !flag && loadjs("http://localhost:8001/CLodopfuncs.js?priority=2");
        });
    }

}

//====获取LODOP对象的主过程：====
function getLodop(oOBJECT, oEMBED) {
    var strHtmInstall = "<br><font color='#FF00FF'>打印控件未安装!点击这里<a href='/files/install_lodop32.exe' target='_self'>执行安装</a>,安装后请刷新页面或重新进入。</font>";
    var strHtmUpdate = "<br><font color='#FF00FF'>打印控件需要升级!点击这里<a href='/files/install_lodop32.exe' target='_self'>执行升级</a>,升级后请重新进入。</font>";
    var strHtm64_Install = "<br><font color='#FF00FF'>打印控件未安装!点击这里<a href='/files/install_lodop64.exe' target='_self'>执行安装</a>,安装后请刷新页面或重新进入。</font>";
    var strHtm64_Update = "<br><font color='#FF00FF'>打印控件需要升级!点击这里<a href='/files/install_lodop64.exe' target='_self'>执行升级</a>,升级后请重新进入。</font>";
    var strHtmFireFox = "<br><br><font color='#FF00FF'>（注意：如曾安装过Lodop旧版附件npActiveXPLugin,请在【工具】->【附加组件】->【扩展】中先卸它）</font>";
    var strHtmChrome = "<br><br><font color='#FF00FF'>(如果此前正常，仅因浏览器升级或重安装而出问题，需重新执行以上安装）</font>";
    var strCLodopInstall = "<br><font color='#FF00FF'>CLodop云打印服务(localhost本地)未安装启动!点击这里<a href='/files/CLodop_Setup_for_Win32NT.exe' target='_self'>执行安装</a>,安装后请刷新页面。</font>";
    var strCLodopUpdate = "<br><font color='#FF00FF'>CLodop云打印服务需升级!点击这里<a href='/files/CLodop_Setup_for_Win32NT.exe' target='_self'>执行升级</a>,升级后请刷新页面。</font>";
    var LODOP;
    try {
        var isIE = (navigator.userAgent.indexOf('MSIE') >= 0) || (navigator.userAgent.indexOf('Trident') >= 0);
        if (needCLodop()) {
            try {
                LODOP = getCLodop();
            } catch (err) {
            }
            ;
            if (!LODOP && document.readyState !== "complete") {
                alert("C-Lodop没准备好，请稍后再试！");
                return;
            }
            ;
            if (!LODOP) {
                if (isIE) document.write(strCLodopInstall); else
                    document.documentElement.innerHTML = strCLodopInstall + document.documentElement.innerHTML;
                return;
            } else {

                if (CLODOP.CVERSION < "2.0.6.8") {
                    if (isIE) document.write(strCLodopUpdate); else
                        document.documentElement.innerHTML = strCLodopUpdate + document.documentElement.innerHTML;
                }
                ;
                if (oEMBED && oEMBED.parentNode) oEMBED.parentNode.removeChild(oEMBED);
                if (oOBJECT && oOBJECT.parentNode) oOBJECT.parentNode.removeChild(oOBJECT);
            }
            ;
        } else {
            var is64IE = isIE && (navigator.userAgent.indexOf('x64') >= 0);
            //=====如果页面有Lodop就直接使用，没有则新建:==========
            if (oOBJECT != undefined || oEMBED != undefined) {
                if (isIE) LODOP = oOBJECT; else  LODOP = oEMBED;
            } else if (CreatedOKLodop7766 == null) {
                LODOP = document.createElement("object");
                LODOP.setAttribute("width", 0);
                LODOP.setAttribute("height", 0);
                LODOP.setAttribute("style", "position:absolute;left:0px;top:-100px;width:0px;height:0px;");
                if (isIE) LODOP.setAttribute("classid", "clsid:2105C259-1E0C-4534-8141-A753534CB4CA");
                else LODOP.setAttribute("type", "application/x-print-lodop");
                document.documentElement.appendChild(LODOP);
                CreatedOKLodop7766 = LODOP;
            } else LODOP = CreatedOKLodop7766;
            //=====Lodop插件未安装时提示下载地址:==========
            if ((LODOP == null) || (typeof(LODOP.VERSION) == "undefined")) {
                if (navigator.userAgent.indexOf('Chrome') >= 0)
                    document.documentElement.innerHTML = strHtmChrome + document.documentElement.innerHTML;
                if (navigator.userAgent.indexOf('Firefox') >= 0)
                    document.documentElement.innerHTML = strHtmFireFox + document.documentElement.innerHTML;
                if (is64IE) document.write(strHtm64_Install); else if (isIE) document.write(strHtmInstall); else
                    document.documentElement.innerHTML = strHtmInstall + document.documentElement.innerHTML;
                return LODOP;
            }
            ;
        }
        ;
        if (LODOP.VERSION < "6.2.0.8") {
            if (needCLodop())
                document.documentElement.innerHTML = strCLodopUpdate + document.documentElement.innerHTML; else if (is64IE) document.write(strHtm64_Update); else if (isIE) document.write(strHtmUpdate); else
                document.documentElement.innerHTML = strHtmUpdate + document.documentElement.innerHTML;
            return LODOP;
        }
        ;
        //===如下空白位置适合调用统一功能(如注册语句、语言选择等):===

        //===========================================================
        return LODOP;
    } catch (err) {
        alert("getLodop出错:" + err);
    }
    ;
};

//style="width:794px;height:1123px;"
function printInit(obj, method) {

    try {
        var LODOP = printReady(obj);
        if (LODOP && LODOP[method]) {
            LODOP[method]();
        } else {
            return LODOP;
        }

    } catch (e) {
        window.alert('调用打印发生异常');
    }
}

function printReady(obj) {
    var LODOP = getLodop();
    LODOP.PRINT_INITA(0, 0, tplInfo.width, tplInfo.height, "打印控件功能演示_Lodop功能_右边距下边距设置1");

    var leftOffset = 0;
    var leftOffTop = 0;
    LODOP.ADD_PRINT_HTM(obj.headerHight, leftOffset, "RightMargin:" + leftOffset + "px", "BottomMargin:" + (obj.footerHight) + "px", obj.main);
    LODOP.SET_PRINT_STYLEA(0, "Vorient", 3);

    LODOP.ADD_PRINT_HTM(leftOffTop, leftOffset, "RightMargin:" + leftOffset + "px", obj.headerHight, obj.header);
    LODOP.SET_PRINT_STYLEA(0, "ItemType", 1);
    LODOP.SET_PRINT_STYLEA(0, "LinkedItem", 1);

    LODOP.ADD_PRINT_HTM(tplInfo.height - obj.footerHight, leftOffset, "RightMargin:" + leftOffset + "px", "BottomMargin:" + (0) + "px", obj.footer);
    LODOP.SET_PRINT_STYLEA(0, "ItemType", 1);
    LODOP.SET_PRINT_STYLEA(0, "LinkedItem", 1);

    return LODOP;
}

/**
 * 打印包裹
 * @param id
 * @param obj
 * @returns {*}
 */
function printWrapper(id, obj, data) {
    $.each(sections, function (i, name) {
        obj[name] = handlebars.compile(obj[name])(data);
    });

    var style = {padding: '5px 50px', display: 'block'};
    var wrapper = $(id).css({overflow: 'auto', width: '0px', height: '0px'}).html('');
    var ele = $('<div/>').css({width: tplInfo.width + 'px'}).appendTo(wrapper);
    var pageheader = $('<div/>').html(obj.header).appendTo(ele).css(style);
    var pagemain = $('<div/>').html(obj.main).appendTo(ele).css(style);
    var pagefooter = $('<div/>').html(obj.footer).appendTo(ele).css(style);

    obj.headerHight = pageheader.height();
    obj.mainHight = pagemain.height();
    obj.footerHight = pagefooter.height();
    return obj;
}

/**
 * 编辑器发生变化
 */
function editorChange() {

    if (editorChangeTimer) {
        clearTimeout(editorChangeTimer);
    }
    editorChangeTimer = setTimeout(function () {

        $('.paperEditor')
            .removeClass("pageheader-" + !!!tplInfo.pageheader)
            .removeClass("pagefooter-" + !!!tplInfo.pagefooter)
            .addClass("pageheader-" + !!tplInfo.pageheader)
            .addClass("pagefooter-" + !!tplInfo.pagefooter)
        ;


        var height = tplInfo.height
            - (tplInfo.pageheader ? $('.paperEditor pageheader').height() : 0)
            - (tplInfo.pagefooter ? $('.paperEditor pagefooter').height() : 0)
            - 20


        $('.paperEditor pagemain').height(height);
        console.log('editorChange');
    }, 100);
}

function editorsHideAllToolbar() {
    tinymce.each(editors, function (v, k) {
        v.toolbarPanel && v.toolbarPanel.hide();
    });
}

function createDate() {
    var arr = ['YYYY-MM-DD HH:mm:ss']
}

var variables = {
    patient: {
        Id: '患者数据ID',
        PatientId: '患者ID',
        Name: '患者姓名',
        NameInput: '姓名输入码',
        Gender: '性别',
        Birthday: '出生日期',
        MaritalStatus: '婚姻状况',
        BloodType: '血型',
        BloodTypeRH: 'RH血型',
        PatientSource: '患者来源',
        PatientBarCode: '患者条形码',
        IdentityCategory: '身份类别',
        IDNumber: '身份证号',
        Citizenship: '国籍',
        Nation: '民族',
        NativePlace: '籍贯',
        WorkUnit: '工作单位',
        WorkStatus: '工作状态',
        Profession: '职业',
        Address: '通讯地址',
        EmailAddress: '邮箱地址',
        ContactName: '联系人姓名',
        ContactNumber: '联系人电话',
        ContactAddress: '联系人地址',
        CurrentAddress: '现住址',
        ContactRelationship: '联系人关系',
        ZipCode: '邮编',
        PermanentAddress: '户口地址',
        PermanentZipCode: '户口邮编',
        Birthplace: '出生地',
        PhoneNumber: '电话',
        CreateDate: '创建时间',
        CreateUserId: '创建人',
    },
    visit: {
        Id: 'id号',
        SerialNumber: '门诊流水号',
        VisitDate: '就诊日期',
        VisitType: '就诊类别',
        InsuranceNumber: '医疗保险号',
        InsuranceType: '医保类别',
        VisitNo: '就诊序号',
        VisitStatus: '就诊状态',
        FirstVisitSign: '初诊标志',
        Doctor: '就诊医生',
        ChargeType: '费别',
        RegisteredDate: '挂号日期',
        RegisteredStatus: '挂号状态',
        VisitDept: '就诊科室',
        Symptom: '症状',
        CreateDate: '创建时间',
        CreateUserId: '创建人',
    },
    other: {
        "date 'YYYY-MM-DD HH:mm:ss'": '日期时间(YYYY-MM-DD HH:mm:ss)',
        "date 'YYYY-MM-DD'": '日期(YYYY-MM-DD)',
        "date 'HH:mm:ss'": '时间(HH:mm:ss)',
        "date 'HH:mm'": '时间(HH:mm)',
    }
};

var variablesMenus = function (editor, key, obj, label) {
    var menus = [];
    if (label) {
        label += ':'
    }
    var createclick = function (v, k, key, editor) {
        return function () {
            editor.insertContent(`{{${key}.${k}}}`);
        }
    };
    tinymce.each(obj, function (v, k) {
        menus.push({text: v, onclick: createclick(v, k, key, editor), var: `${key}|${k}`})
    });
    return menus;
};

function init(name) {
    var selector = ".paperEditor page" + name,
        toolbar = "#toolbar page" + name
    tinymce.init({
        pageheader: true,
        pagefooter: true,
        selector: selector,
        language: 'zh_CN',
        /*language_url: "js/tinymce/langs/zh_CN.js",*/
        inline: true,
        //inlineToolBarautoHide: false,
        defaultMenus: {emr: {title: 'Emr'}},
        fixed_toolbar_container: toolbar,
        onToolbarHide: function (panel) {
            editorsHideAllToolbar();
            panel && panel.show();
            return true;
        },
        onToolbarShow: editorsHideAllToolbar,
        //end_container_on_empty_block: true,
        menubar: 'file edit insert view format table tools emr',
        plugins: [
            'advlist autolink lists link image charmap print preview hr anchor pagebreak',
            'searchreplace wordcount visualblocks visualchars code fullscreen',
            'insertdatetime media nonbreaking save table contextmenu directionality',
            'emoticons template paste textcolor colorpicker textpattern imagetools',
            'emrDesign'
        ],
        toolbar1: 'insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | forecolor backcolor emoticons | bullist numlist outdent indent | link image | print preview media',
        setup: function (editor) {
            editors[name] = editor;
            editor.addMenuItem('emrPreView', {
                text: '打印预览',
                context: 'emr',
                onclick: function () {
                    let obj = apis.get();
                    obj = printWrapper('#printWrapper', JSON.parse(obj),variables);
                    printInit(obj, 'PREVIEW');
                }
            });
            editor.addMenuItem('emrInsertVariable-patient', {
                separator: 'before',
                text: '患者变量',
                context: 'emr',
                menu: variablesMenus(editor, 'patient', variables.patient, '患者')
            });

            editor.addMenuItem('emrInsertVariable-visit', {
                text: '就诊变量',
                context: 'emr',
                menu: variablesMenus(editor, 'visit', variables.visit, '就诊')
            });
            editor.addMenuItem('emrInsertVariable-other', {
                text: '其它变量',
                context: 'emr',
                menu: variablesMenus(editor, 'other', variables.other, '')
            });

            if (name === "main") {
                setTimeout(function () {
                    if (!editor.destroyed) {
                        editor.focus();
                    }
                }, 300);
            }
            editor.on("change", function () {
                editorChange();
            });
            editor.on('pageheader', function () {
                tplInfo.pageheader = this.pageheader;
                editorChange();
            });
            editor.on('pagefooter', function () {
                tplInfo.pagefooter = this.pagefooter;
                editorChange();
            });
        },
        content_css: [
            '/css/emrDesign.css'
        ]
    });
};

const sections = ["header", "main", "footer"];
const apis = {
    init: function (cb) {
        require('../../res/tinymce/tinymce');
        $('.paperEditor,.container.editor').css({width: tplInfo.width + 'px', height: tplInfo.height + 'px'});
        tinymce.EditorManager.overrideDefaults({base_url: '/tinymce/'});

        $.each(sections, function (i, name) {
            init(name);
        });
    },
    destroy: function () {
        $.each(editors, (k, v) => {
            v.destroy();
        });
    },
    set: function (contents) {
        $.each(sections, function (i, name) {
            if (contents[name]) {
                $(".paperEditor page" + name).html(contents[name]);
            }
        });
    },
    get: function () {
        const contents = {};
        $.each(sections, function (i, name) {
            const editor = editors[name];
            if (editor) {
                const content = trim(editor.getContent());
                if (content) {
                    contents[name] = content;
                }
            }
        });
        return JSON.stringify(contents);
    },
    printInit: printInit,
    printCheck: printCheck,
    printWrapper: printWrapper
};
module.exports = apis;
